<?php
namespace app\admin\controller;

use think\Controller;
use think\Exception;
use think\Request;

/**
 * Class WxLogin
 * @package app\admin\controller    app微信登录和手机站微信网页授权登录
 */
class WxLogin extends Controller 
{
    /*
     * app微信登录
     */
    public function app_login(Request $request)
    {
        //app提供access_token和openid
        $data = $request->param();
        //获取用户微信基本信息
        $userInfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$data['openid'];
        $info = self::curl_get_contents($userInfo_url);
        //包含微信个人信息的数组
        $user_info = json_decode($info, true);
        //进行比对登录或者注册,注册时官方建议微信头像最好保存到本地,微信昵称可能含有表情所以需要数据库更改编码为utf8mb4保存
    }
    /*
     * 微信网页授权登录->生成回调地址到登录页
     */
    public function oauth2_login(Request $request)
    {
        //开通公众号登录权限,填写公共号设置内的回调域名
        //设置回调地址,需要对地址进行UrlEncode编码,如有业务需要,可以带参数
        $redirect_uri =  urlencode($request->domain()."/index.php/admin/wx_login/redirect_uri");
        //此地址是微信登录按钮的跳转链接
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect&wechat_redirect";
        return $this->fetch('',[
           'url' => $url,
        ]);
    }
    /*
     * 授权后的回调地址
     */
    public function redirect_uri(Request $request)
    {
        //用户授权后,地址栏上会带着code码
        $data = $request->param();
        //以code换取网页授权access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=".$data['code']."&grant_type=authorization_code";
        $json = self::curl_get_contents($url);
        $arr = json_decode($json,true);
        //如果返回的数据中含有errmsg,说明登录失败
        if (array_key_exists('errmsg',$arr)) throw new Exception($arr['errmsg']);
        //以token和openid获取用户信息
        $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$arr['access_token']."&openid=".$arr['openid']."&lang=zh_CN";
        $info = self::curl_get_contents($url2);
        //获取到用户信息的数组
        $user_info = json_decode($info,true);
        //进行比对登录或者注册
    }
    /*
    * curl->get获取内容
    */
    function curl_get_contents($url,$timeout=30) {
        $curlHandle = curl_init();
        curl_setopt( $curlHandle , CURLOPT_URL, $url );
        curl_setopt( $curlHandle , CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $curlHandle , CURLOPT_TIMEOUT, $timeout );
        curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, FALSE);   //屏蔽ssl证书和host
        curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST, FALSE);
        $result = curl_exec( $curlHandle );
        curl_close( $curlHandle );
        return $result;
    }
}